﻿using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MOKA.TPM.Application.Enum;
using MOKA.TPM.Entity;
using MOKA.TPM.Service.Dto;
using MOKA.TPM.Utility.Const;
using SqlSugar;
using System.ComponentModel;

namespace MOKA.TPM.Service;

/// <summary>
/// 服务
/// </summary>
[ApiDescriptionSettings(TPMConst.GroupName, Order = 860)]
public class Service_T_USER : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<T_USER> _rep;
    private readonly UserManager _userManager;
    private IHttpContextAccessor _accessor;//获取请求上下文_userRepository
    private readonly ISqlSugarClient _db;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="db"></param>
    /// <param name="rep"></param>
    /// <param name="userManager"></param>
    /// <param name="accessor"></param>
    public Service_T_USER(ISqlSugarClient db, SqlSugarRepository<T_USER> rep, UserManager userManager, IHttpContextAccessor accessor)
    {
        _db = db;
        _rep = rep;
        _userManager = userManager;
        _accessor = accessor;
    }

    /// <summary>
    /// 获取关联表
    /// </summary>
    /// <param name="querey"></param>
    /// <returns></returns>
    private ISugarQueryable<T_USER> GetIncludes(ISugarQueryable<T_USER> querey)
    {
        var querey1 = querey

       ;
        return querey1;
    }

    /// <summary>
    /// 获取Select
    /// </summary>
    /// <param name="querey"></param>
    /// <returns></returns>
    private ISugarQueryable<T_USEROutput> GetSelect(ISugarQueryable<T_USER> querey)
    {
        var dto = querey.Select((a) => new T_USEROutput()
        {
            UserName = a.UserName.SelectAll(),
        });
        return dto;
    }

    /// <summary>
    /// 获取Mapper
    /// </summary>
    /// <param name="querey"></param>
    /// <returns></returns>
    private ISugarQueryable<T_USEROutput> GetMapper(ISugarQueryable<T_USEROutput> querey)
    {
        return querey.Mapper((item) =>
        {
            //Mapster映射转换，不能有SQL
            //TypeAdapterConfig config = new TypeAdapterConfig()
            //.ForType<ContractFile, ContractFileOutput>()
            //.IgnoreIf((src, dest) => src.File == null, "Id", "Name", "FileType", "FileName", "Suffix", "FilePath", "SizeKb", "Url")
            //    .Map(dest => dest.Id, src => src.File.Id)
            //    .Map(dest => dest.Name, src => src.File.Id + src.File.Suffix)
            //.Config
            //.ForType<JToken, JToken>()
            //    .MapWith(json => json)
            //.Config;
            //item.ContractBody = item.ContractBodyIn.Adapt<List<ContractFileOutput>>(config);
        });
    }

    /// <summary>
    /// 获取分页列表 🧩
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [AllowAnonymous]
    [DisplayName("获取分页列表")]
    public async Task<SqlSugarPagedList<T_USEROutput>> Page(PageT_USERInput input)
    {
        var querey = _rep.AsTenant().QueryableWithAttr<T_USER>();
        var quereyWithIncludes = GetIncludes(querey)
         .WhereIF(!string.IsNullOrEmpty(input.UserName?.Trim()), a => a.UserName.Contains(input.UserName ?? "".Trim()))
            .WhereIF(!string.IsNullOrEmpty(input.UserRemark?.Trim()), a => a.UserRemark.Contains(input.UserRemark ?? "".Trim()))
        //.LeftJoin<FlowStateinfo>((a, d) => a.UserName == d.SourceId)
       ;
        var quereyWithSelect = GetSelect(quereyWithIncludes);
        var lists = await GetMapper(quereyWithSelect)
            .OrderBuilder(input, "", "UserName") //(input, "a.", "PartNo", false)
            .ToPagedListAsync(input.Page, input.PageSize);

        //使用.ThenMapper继续查询有字典详细表
        return lists;
    }

    /// <summary>
    /// 获取列表🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取列表")]
    [AllowAnonymous]
    public async Task<List<T_USEROutput>> GetList([FromQuery] GetT_USERInput input)
    {
        var querey = _rep.AsTenant().QueryableWithAttr<T_USER>();
        var quereyWithIncludes = GetIncludes(querey)
            .WhereIF(!string.IsNullOrEmpty(input.UserName?.Trim()), a => a.UserName.Contains(input.UserName ?? "".Trim()))
            .WhereIF(!string.IsNullOrEmpty(input.UserRemark?.Trim()), a => a.UserRemark.Contains(input.UserRemark ?? "".Trim()))
            //.LeftJoin<FlowStateinfo>((a, d) => a.UserName == d.SourceId)
            .OrderByDescending(a => a.UserName)
        ;
        var quereyWithSelect = GetSelect(quereyWithIncludes);
        var lists = await GetMapper(quereyWithSelect)
            .Take(20)//为了性能，只取20个。
            .ToListAsync();

        //使用.ThenMapper继续查询有字典详细表
        return lists;
    }

    /// <summary>
    /// 获取单个对象(根据主键) 🧩
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "One")]
    [DisplayName("获取单个对象(根据主键)")]
    [AllowAnonymous]
    public async Task<T_USEROutput> GetOne([FromQuery] T_USERInput input)
    {
        var querey = _rep.AsTenant().QueryableWithAttr<T_USER>();
        var quereyWithIncludes = GetIncludes(querey)
        //.LeftJoin<FlowStateinfo>((a, d) => a.UserName == d.SourceId)
            .WhereIF(!string.IsNullOrEmpty(input.UserName), a => a.UserName == input.UserName)
       ;
        var quereyWithSelect = GetSelect(quereyWithIncludes);
        var lists = await GetMapper(quereyWithSelect)
            .SingleAsync();

        //使用.ThenMapper继续查询有字典详细表
        return lists;
    }

    /// <summary>
    /// 添加 🧩
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    [DisplayName("添加")]
    [AllowAnonymous]
    public async Task<bool> AddData(AddT_USERInput input)
    {
        var entity = input.Adapt<T_USER>(); //将AddT_USERInput转成T_USER

        //entity.Code = "thisCode"; //后台生成字段值

        //启动事务
        using (var uow = _db.CreateContext())
        {
            var ret = await _rep.AsInsertable(entity).EnableDiffLogEvent().ExecuteReturnEntityAsync();//插入后返回实体

            //提交事务
            uow.Commit();
            return ret != null;
        }
    }

    /// <summary>
    /// 更新 🧩
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    [DisplayName("更新")]
    [AllowAnonymous]
    public async Task<bool> UpdateData(UpdateT_USERInput input)
    {
        //主键是否存在
        var isExist = await _rep.IsAnyAsync(u => u.UserName == input.UserName);
        if (!isExist)
            throw Oops.Oh(TpmErrorCodeEnum.FieldValueNotExist, "UserName", input.UserName);

        var entity = input.Adapt<T_USER>(); //将UpdateT_USERInput转成T_USER

        //启动事务
        using (var uow = _db.CreateContext())
        {
            bool ret = await _rep.AsUpdateable(entity).IgnoreNullColumns().EnableDiffLogEvent().ExecuteCommandAsync() > 0;

            //提交事务
            uow.Commit();
            return ret;
        }
    }

    /// <summary>
    /// 删除 🧩
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    [DisplayName("删除")]
    [AllowAnonymous]
    public async Task<bool> DeleteData(DeleteT_USERInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.UserName == input.UserName) ?? throw Oops.Oh(TpmErrorCodeEnum.FieldValueNotExist, "UserName", input.UserName);

        //启动事务
        using (var uow = _db.CreateContext())
        {
            bool ret = await _rep.Context.Deleteable(entity).EnableDiffLogEvent().ExecuteCommandAsync() > 0;

            //提交事务
            uow.Commit();
            return ret;
        }
    }

    /// <summary>
    /// 修改部分数据 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "UpdateSome"), HttpPost]
    [DisplayName("修改部分数据")]
    [AllowAnonymous]
    public async Task<bool> UpdateSomeData(UpdateSomeT_USERInput input)
    {
        //主键是否存在
        var isExist = await _rep.IsAnyAsync(u => u.UserName == input.UserName);
        if (!isExist)
        {
            throw Oops.Oh(TpmErrorCodeEnum.FieldValueNotExist, "UserName", input.UserName);
        }

        var entity = input.Adapt<T_USER>(); //将UpdateT_USERInput转成T_USER

        //启动事务
        using (var uow = _db.CreateContext())
        {
            bool ret = await _rep.AsUpdateable(entity).UpdateColumns(it => new { it.UserName, }).ExecuteCommandAsync() > 0;

            //提交事务
            uow.Commit();
            return ret;
        }
    }

    /// <summary>
    /// 批量添加
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "AddRange"), HttpPost]
    [DisplayName("批量添加")]
    [AllowAnonymous]
    public async Task<int> AddBulkData(List<T_USER> input)
    {
        //启动事务
        using (var uow = _db.CreateContext())
        {
            int ret = await _rep.Context.Insertable(input).ExecuteCommandAsync();
            //不需要上传详细表了

            //提交事务
            uow.Commit();
            return ret;
        }
    }
}